import { useSizeObserver } from "@/hooks/useSizeObserver"
import { List as _List, GetProps } from "antd"
import classNames from "classnames"
import VirtualList from "rc-virtual-list"
import styles from "./List.module.scss"
import { ReactNode, UIEventHandler } from "react"

export interface IListProps<Item = any> extends GetProps<typeof VirtualList<Item>> {
  classnames?: {
    list_root?: string;
    list?: string;
    list_inner?: string;
  },
  reach_end_height?: number
  on_reach_end?(): void;
  others?: ReactNode;
}
export function List<Item = any>(props: IListProps<Item>) {
  const [ref_containter, , continer_height] = useSizeObserver<HTMLDivElement>()
  const {
    className, classnames, on_reach_end, onScroll, reach_end_height = 1000,
    others, ..._p
  } = props;
  const _classname = classNames(styles.list_container, className)
  const handleScroll: UIEventHandler<HTMLElement> = (e) => {
    onScroll?.(e);
    const { scrollTop, clientHeight, scrollHeight } = e.target as HTMLElement;
    const reach_end = scrollTop + clientHeight >= scrollHeight - 1000;
    if (reach_end) on_reach_end?.()
  };
  return (
    <div ref={ref_containter} className={_classname}>
      {others}
      <_List
        className={classnames?.list}
        rootClassName={classnames?.list_root}>
        <VirtualList
          height={continer_height}
          className={classnames?.list_inner}
          {..._p}
          onScroll={handleScroll} />
      </_List>
    </div>
  )
}
List.Item = _List.Item
List.classnames = {
  list_container: styles.list_container
} as const